A Python dictionary is a mutable data structure that can be used to associate keys with values. They are created using {}
braces. You can think of dictionaries as lists, except that instead of extracting elements by their position you extract them using their keys. One way of creating them follows.
In [1]:
numbers = {1: "one", 2: "two", 3: "three"}
numbers
Out[1]:
In the numbers
dictionary the keys are 1
, 2
and 3
and their corresponding values are "one"
, "two"
and "three"
. Extracting a value from a dictionary is very similar to extracting an element from a list.
In [2]:
numbers[2]
Out[2]:
In [3]:
elements = {
"H": "Hydrogen",
"He": "Helium",
"Li": "Lithium",
}
elements
Out[3]:
In [4]:
elements["H"]
Out[4]:
In [5]:
houses = {
("Harry", "Potter"): "Gryffindor",
("Hermione", "Granger"): "Gryffindor",
("Draco", "Malfoy"): "Slytherin",
("Cho", "Chang"): "Ravenclaw"
}
houses
Out[5]:
In [6]:
houses[("Harry", "Potter")]
Out[6]:
In [7]:
# Adding a mapping.
elements["Au"] = "Gold"
elements
Out[7]:
In [8]:
# Removing a mapping.
elements.pop("H")
Out[8]:
In [9]:
elements
Out[9]:
Much like with lists, attempting to access an element that doesn't exist will result in an error.
In [10]:
elements["Ag"]
It is possible to check if a key is in a dictionary.
In [11]:
("Harry", "Potter") in houses
Out[11]:
In [12]:
("Ronald", "Weasley") in houses
Out[12]: